﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Data;

namespace LuDragon.Common.Utils
{
    public static class JsonHelper
    {
        /// <summary>
        /// Json字符串转对象
        /// </summary>
        /// <param name="Json">待反序列化Json字符串</param>
        /// <returns></returns>
        public static object ToJson(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject(Json);
        }
        /// <summary>
        /// 对象转Json字符串
        /// </summary>
        /// <param name="obj">待序列化对象</param>
        /// <returns></returns>
        public static string ToJson(this object obj)
        {
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            return JsonConvert.SerializeObject(obj, timeConverter);
        }
        /// <summary>
        /// 对象转Json字符串--自定义时间格式
        /// </summary>
        /// <param name="obj">待序列化对象</param>
        /// <param name="datetimeformats">时间格式；如：yyyy-MM-dd HH:mm:ss</param>
        /// <returns></returns>
        public static string ToJson(this object obj, string datetimeformats)
        {
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = datetimeformats };
            return JsonConvert.SerializeObject(obj, timeConverter);
        }
        /// <summary>
        /// Json字符串转实体对象
        /// </summary>
        /// <typeparam name="T">实体对象</typeparam>
        /// <param name="Json">待反序列化Json字符串</param>
        /// <returns></returns>
        public static T ToObject<T>(this string Json)
        {
            return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json);
        }
        /// <summary>
        /// Json字符串转实体对象集合
        /// </summary>
        /// <typeparam name="T">实体对象</typeparam>
        /// <param name="Json">待反序列化Json字符串</param>
        /// <returns></returns>
        public static List<T> ToList<T>(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject<List<T>>(Json);
        }
        /// <summary>
        /// Json字符串转DataTable对象
        /// </summary>
        /// <param name="Json">待反序列化Json字符串</param>
        /// <returns></returns>
        public static DataTable ToTable(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject<DataTable>(Json);
        }
        /// <summary>
        /// Json字符串转Json对象
        /// </summary>
        /// <param name="Json">待反序列化Json字符串</param>
        /// <returns></returns>
        public static JObject ToJObject(this string Json)
        {
            return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace("&nbsp;", ""));
        }
    }
}
